<template>
  <div class="app-container">
    <div>
      <!-- 条件栏 -->
      <NewPageFilter
        v-model:query="filterInfo.query.queryParams"
        :filter-list="filterInfo.searchList"
        :filter-btn="filterInfo.searchBtn"
        :slipSelectRequest="slipSelectRequest"
      >
      </NewPageFilter>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList"></NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :checkBox="false"
        :listen-height="true"
        rowKey="_index"
        :handle="tableInfo.handle"
        :tab-index="true"
        :summary="true"
        :summaryFieldList="tableInfo.summaryFieldList"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        @exChange="exChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-expand>
          <PageTable
            class="expandTable"
            v-model:data="expandTableInfo.data"
            :checkBox="false"
            :listen-height="true"
            rowKey="_index"
            :tab-index="true"
            :field-list="expandTableInfo.fieldList"
            :pager="false"
            style="background: #fceacb"
          />
        </template>
      </TableContainer>
    </div>
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
  </div>
</template>

<script setup name="inventoryBatchQuery">
import { getDepotAll, getDeptAll } from '@/api/core'
import {
  getInventoryBatchQueryPage,
  printInventoryBatchQuery,
  excelInventoryBatchQuery,
  getInventoryBatchQueryGroupByProductAll,
} from '@/api/dataQuery'

import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import _ from 'lodash'
import { fatchTemplateByCode } from '@/api/base'
const SetPreference = defineAsyncComponent(() =>
  import('@/components/SetPreference/setPreferenceNoQuery')
)
const { proxy } = getCurrentInstance()
const preferenceInfo = ref({
  visible: false,
})
const filterInfo = ref({
  query: {
    queryParams: {
      depotIdMult: '',
      deptIdMult: '',
      productId: '',
      isConsignBusiness: '',
    },
    sortString: '',
    customizeUserVO: {},
    queryMap: {},
  },
  searchList: [
    {
      label: '产品',
      value: 'productId',
      asValue: 'productId',
      componentType: 'select-product',
      checkBox: true,
      highlightRow: true,
      event: search,
    },
    {
      label: '供应商',
      value: 'supplierName',
      asValue: 'supplierId',
      componentType: 'select-supplier',
      checkBox: true,
      highlightRow: true,
      event: search,
    },

    {
      componentType: 'slip-select',
      label: '仓库',
      value: 'depotIdMult',
      api: getDepotAll,
      query: {
        status: '1',
        depotAuth: 'id',
        searchType: 'depot',
        useTypeId: '1',
      },
      multiple: true,
      event: search,
    },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      asValue: 'isConsignBusiness',
      componentType: 'select-model',
      code: 'yes_or_no',
      event: search,
    },
    {
      label: '是否暂估入库',
      value: 'isEstimationStockBusinessValue',
      asValue: 'isEstimationStockBusiness',
      componentType: 'select-model',
      code: 'yes_or_no',
      event: search,
    },
    {
      label: '入库批次号',
      value: 'storeBatchNumber',
      componentType: 'input',
      event: search,
    },
  ],
  searchBtn: [{ type: 'button', label: '搜索', event: search }],
  btnList: [
    {
      type: 'button',
      label: '打印',
      event: print,
      show: proxy.$permission('inventoryBatchQuery:printDetail'),
    },
    {
      type: 'button',
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('inventoryBatchQuery:excelDetail'),
    },
  ],
})
const expandTableInfo = ref({
  data: [],
  fieldList: [
    {
      label: '数量',
      value: 'qty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '冻结数量',
      value: 'frozenQty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '待入库数量',
      value: 'pendStoreQty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '单价',
      value: 'price',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '生产批号',
      value: 'batchNumber',
    },
    {
      label: '生产日期',
      value: 'productionDate',
    },
    {
      label: '失效日期',
      value: 'validityDate',
    },
  ],
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  selections: [],
  fieldList: [],
})
const slipSelectRequest = ref(true)
const productList = ref([])

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function getList() {
  tableInfo.value.refresh = Math.random()
}
function search() {
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function exportExcel() {
  excelInventoryBatchQuery(
    proxy.$fn.delEmptyAttribute(filterInfo.value.query)
  ).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function print() {
  fatchTemplateByCode({
    resourceCode: 'inventoryBatchQuery:printDetail',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      let params = {
        customizeDto: filterInfo.value.query,
      }
      printInventoryBatchQuery(params).then((resp) => {
        if (resp && resp.success) {
          let data = proxy.$fn.deepClone(resp.data)
          let newData = data.map((item) => {
            return {
              ...item,
              ...item.orderInfo,
            }
          })
          proxy.$lodop.preview(temp, newData)
        }
      })
    }
  })
}

function handleEvent(event, data) {
  switch (event) {
    case 'list':
      tableInfo.value.data = data.map((item, index) => {
        return {
          ...item,
          _index: index + 1,
        }
      })
      break
  }
}

function exChange(data, expandedRows) {
  if (expandedRows.length > 0) {
    let params = {
      price: data.price,
      productId: data.productId,
      supplierId: data.supplierId,
      depotId: data.depotId,
    }
    getInventoryBatchQueryGroupByProductAll(params).then((resp) => {
      if (resp && resp.success) {
        let data = resp.data.map((item, index) => {
          return {
            ...item,
            _index: index,
          }
        })
        expandTableInfo.value.data = data
      }
    })
  }
}

function getCustomize(SelectRequest = true) {
  let param = {
    tableKey:
      'inventoryBatchFoldQuery-com.slip.spd.entity.vo.stock.DepotStockVO',
  }
  getCustomizeSetting(param).then((res) => {
    let data = res.data
    filterInfo.value.query.customizeUserVO = data
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList.forEach((item) => {
        item.show = true
      })
      slipSelectRequest.value = SelectRequest
      tableInfo.value.api = getInventoryBatchQueryPage
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      getList()
    }
  })
}
onMounted(() => {
  let obj = {
    expand: {
      label: '',
      value: 'expand',
      columnType: 'expand',
      type: 'slot',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
})
</script>

<style scoped lang="scss">
:deep(.el-table .el-table__expanded-cell[class*='cell']) {
  background: #fceacb !important;
}
:deep(.expandTable .el-table tr),
:deep(.expandTable .el-table td),
:deep(.expandTable .el-table th) {
  background: #fceacb !important;
}
</style>
